package com.zj.web.controller;

import com.zj.service.FileDeduplicationService;
import com.zj.util.FileTypeValidator;
import com.zj.web.bean.ResponseResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@Log
@Tag(name = "文件上传接口",description = "支持将文件上传到OSS的API,支持的文件类型")
public class FileUploadController {
    @Autowired
    private FileDeduplicationService fileDeduplicationService;
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @Operation(summary = "文件上传",description = "支持将文件上传到OSS的API,支持的文件类型有：jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx")
    public ResponseEntity<ResponseResult> uploadFile(@RequestPart("file") MultipartFile[] files){
        if (files==null || files.length==0){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ResponseResult.builder().code(0).msg("文件不能为空").build());
        }
        List<String> fileUrls=new ArrayList<>();
        for (MultipartFile file : files) {
            if(file.isEmpty()){
                continue;
            }
            String contentType=file.getContentType();
            String originalFilename=file.getOriginalFilename(); //文件名
            if(!FileTypeValidator.isAllowedFileType(contentType,originalFilename)){
                //注意：这样写的话，只要有一个文件类型不被允许，就会返回错误信息，而不是继续上传其他文件
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(
                        ResponseResult.builder().code(0).msg("文件类型不被允许："+originalFilename).build()
                );
            }
            try {
                String fileUrl=fileDeduplicationService.processAndGetFileUrl(file);
                fileUrls.add(fileUrl);
            } catch (Exception e) {
                e.printStackTrace();
                log.severe("文件上传失败的文件名："+originalFilename);
            }
        }
        if (fileUrls.size()>0){
            log.info("上传到OSS成功，文件地址为"+fileUrls);
            return ResponseEntity.status(HttpStatus.OK).body(ResponseResult.builder().code(1).msg("文件上传成功").data(fileUrls).build());
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponseResult.builder().code(0).msg("文件上传失败").build());
    }
}
